package com.bitejiuyeke.job_publish.mq;

import com.bitejiuyeke.job_publish.config.RabbitMQConfig;
import com.bitejiuyeke.job_publish.enums.VerifyCodeTargetEnum;
import com.bitejiuyeke.job_publish.mq.model.OfferedMQ;
import com.bitejiuyeke.job_publish.mq.model.VerificationCodeMQ;
import com.bitejiuyeke.job_publish.utils.MailUtils;
import com.bitejiuyeke.job_publish.utils.SMSUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

/**
 * @Author 比特就业课
 */
@Slf4j
@Component
public class MQConsumer {

    @Resource
    private MailUtils mailUtils;
    @Resource
    private SMSUtils smsUtils;
    @Value("${sms.template-verification-code}")
    private String templateVerificationCode;
    @Resource
    private ThreadPoolTaskExecutor threadPool;

    /**
     * 监听验证码的消息队列
     *
     * @param message 验证码消息
     */
    @RabbitListener(queues = RabbitMQConfig.BITE_JOB_V_CODE_QUEUE_NAME)
    public void receiveVerificationCodeMessage(VerificationCodeMQ message) {
        if (message == null) {
            // 直接返回
            return;
        }
        // 任务提交到线程池
        threadPool.execute(() -> procSendCode(message));
    }

    // 发送验证码
    private void procSendCode(VerificationCodeMQ message) {
        // 获取发送验证码目标类型
        VerifyCodeTargetEnum targetEnum = VerifyCodeTargetEnum.valueOf(message.getType());
        switch (targetEnum) {
            case PHONE:
                // 短信
                smsUtils.sendMessage(templateVerificationCode,
                        message.getTargetNum(),
                        "{\"code\":\"" + message.getCode() + "\"}");
                break;
            case EMAIL:
                // 邮件
                mailUtils.sendSampleMail(message.getTargetNum(),
                        "比特校园兼职系统验证码",
                        "本次验证码为：" + message.getCode());
                break;
        }
    }

    /**
     * 监听Offer的消息队列
     *
     * @param message Offer消息
     */
    @RabbitListener(queues = RabbitMQConfig.BITE_JOB_OFFERED_QUEUE_NAME)
    public void receiveOfferMessage(OfferedMQ message) {
        if (message == null) {
            // 直接返回
            return;
        }
        // 任务提交到线程池
        threadPool.execute(() -> procOffered(message));
    }

    // 处理Offer
    private void procOffered(OfferedMQ message) {
        // 发送邮件
        mailUtils.sendSampleMail(message.getTargetNum(),
                "职位邀约状态已更新 -- 比特校园兼职系统",
                message.getContent());
    }
}
